<?php

namespace app\job\queue;

use app\common\enum\AliJobTypeEnum;
use app\common\model\AliJob;
use think\facade\Log;
use think\queue\Job;
use app\common\library\aliyuns\MtsClient;
use app\common\model\fp\PostMedia;
use think\Exception;

class MpsSnapshotJob
{
    public function fire(Job $job, $data)
    {
        if ($job->attempts() > 3) {
            //通过这个方法可以检查这个任务已经重试了几次了
            $job->failed($data);
            $job->delete();
            return;
        }

        try {
            $postMedia = PostMedia::initModel($data['user_id'])->where('post_id', $data['post_id'])->select()->toArray();
            //视频处理
            if (isset($postMedia[0]) && $postMedia[0]['media_type'] == 'video') {
                $object = $postMedia[0]['media_url'];
                //视频截图
                $pathInfo = pathinfo($object);
                $output = $pathInfo['dirname'] . '/' . $pathInfo['filename'] . '_cover_{Count}.jpg';
                $snapshotJob = MtsClient::getInstance()->snapshotJobAsync($object, $output);
                if (in_array($snapshotJob['SnapshotJob']['State'], ['Submitted', 'Success'])) {
                    $insert = [
                        'type' => AliJobTypeEnum::SNAPSHOT->value,
                        'user_id' => $data['user_id'],
                        'audit_id' => $data['audit_id'],
                        'job_id' => $snapshotJob['SnapshotJob']['Id'],
                        'media_id' => $postMedia[0]['id'],
                        'request_result' => json_encode($snapshotJob, JSON_UNESCAPED_UNICODE),
                    ];
                    //记录截图任务
                    AliJob::create($insert);
                } else {
                    throw new Exception('截图任务提交失败:' . json_encode($snapshotJob));
                }
            }

            $job->delete();
        } catch (\Throwable $e) {
            Log::channel('job')->error($e->getMessage() . PHP_EOL . $e->getTraceAsString());
            throw $e;
        }
    }
}